package com.getpebble.android.framework.endpoint;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.media.AudioManager;
import android.os.SystemClock;
import android.view.KeyEvent;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.R;
import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.Music;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.framework.endpoint.EndpointRequest.EndpointAction;
import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.protocol.inbound.PblInboundMusicMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundMusicMessage.MusicControlCommand;
import com.getpebble.android.framework.protocol.outbound.PblOutboundMusicNowPlayingMessage;
import com.getpebble.android.framework.receiver.MusicReceiver;
import com.getpebble.android.framework.receiver.MusicReceiver.MusicInfo;
import com.google.common.collect.ImmutableSet;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.Set;

public class MusicControlEndpoint extends RequestableEndpoint {
    private static final String TAG = MusicControlEndpoint.class.getSimpleName();
    private final AudioManager mAudioManager;
    private ResolveInfo mCachedTarget = null;
    private final IEndpointMessageSender mMessageSender;
    private final PblPreferences mPreferences;

    static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction = new int[EndpointAction.values().length];
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand = new int[MusicControlCommand.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[EndpointAction.UPDATE_MUSIC_NOW_PLAYING.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand[MusicControlCommand.PLAY_PAUSE.ordinal()] = 1;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand[MusicControlCommand.NEXT_TRACK.ordinal()] = 2;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand[MusicControlCommand.PREVIOUS_TRACK.ordinal()] = 3;
            } catch (NoSuchFieldError e4) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand[MusicControlCommand.VOLUME_UP.ordinal()] = 4;
            } catch (NoSuchFieldError e5) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand[MusicControlCommand.VOLUME_DOWN.ordinal()] = 5;
            } catch (NoSuchFieldError e6) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand[MusicControlCommand.GET_NOW_PLAYING.ordinal()] = 6;
            } catch (NoSuchFieldError e7) {
            }
        }
    }

    public MusicControlEndpoint(PblPreferences preferences, Context context, IEndpointMessageSender messageSender) {
        if (preferences == null) {
            throw new IllegalArgumentException("Preferences cannot be null");
        } else if (context == null) {
            throw new IllegalArgumentException("Context cannot be null");
        } else if (messageSender == null) {
            throw new IllegalArgumentException("messageSender cannot be null");
        } else {
            this.mAudioManager = (AudioManager) context.getSystemService("audio");
            this.mPreferences = preferences;
            this.mMessageSender = messageSender;
        }
    }

    private Context getContext() {
        return PebbleApplication.getAppContext();
    }

    private void sendMusicInfo() {
        MusicInfo musicInfo = MusicReceiver.getMusicInfo();
        if (musicInfo == null) {
            Trace.warning(TAG, "musicInfo is null");
            return;
        }
        this.mMessageSender.sendMessage(new PblOutboundMusicNowPlayingMessage(musicInfo.mArtist, musicInfo.mAlbum, musicInfo.mTrack));
    }

    public void onMessageReceived(PblInboundMusicMessage message) {
        if (message == null) {
            Trace.error(TAG, "Received null message, dropping");
            return;
        }
        MusicControlCommand command = message.getMusicControlCommand();
        Context context = getContext();
        if (context == null) {
            Trace.warning(TAG, "Dropping music message; context is null");
            return;
        }
        ResolveInfo targetInfo = Music.getPreferredMusicPlayer(context, this.mPreferences);
        switch (AnonymousClass1.$SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundMusicMessage$MusicControlCommand[command.ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                forwardOrBroadcastKeycode(context, targetInfo, 85);
                return;
            case SMTPMessage.RETURN_HDRS /*2*/:
                forwardOrBroadcastKeycode(context, targetInfo, 87);
                return;
            case ListInfo.INDETERMINATE /*3*/:
                forwardOrBroadcastKeycode(context, targetInfo, 88);
                return;
            case SMTPMessage.NOTIFY_DELAY /*4*/:
                this.mAudioManager.adjustStreamVolume(3, 1, 9);
                return;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsHeaderTextAppearance /*5*/:
                this.mAudioManager.adjustStreamVolume(3, -1, 9);
                return;
            case R.styleable.WalletFragmentStyle_maskedWalletDetailsBackground /*6*/:
                sendMusicInfo();
                return;
            default:
                Trace.error(TAG, "Received unsupported music control command: " + command);
                return;
        }
    }

    private void forwardOrBroadcastKeycode(Context context, ResolveInfo targetInfo, int keyCode) {
        if (targetInfo == null) {
            broadcastMediaKeyIntents(context, keyCode);
        } else {
            forwardKeyToReceiver(context, targetInfo, keyCode);
        }
    }

    private static void broadcastMediaKeyIntents(Context context, int keycode) {
        long eventtime = SystemClock.uptimeMillis();
        Intent downIntent = new Intent("android.intent.action.MEDIA_BUTTON", null);
        downIntent.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(eventtime, eventtime, 0, keycode, 0));
        context.sendOrderedBroadcast(downIntent, null);
        Intent upIntent = new Intent("android.intent.action.MEDIA_BUTTON", null);
        upIntent.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(eventtime, eventtime, 1, keycode, 0));
        context.sendOrderedBroadcast(upIntent, null);
    }

    private void forwardKeyToReceiver(Context context, ResolveInfo resolveInfo, int keyCode) {
        boolean shouldLaunchTarget = false;
        if (this.mCachedTarget == null) {
            this.mCachedTarget = resolveInfo;
            shouldLaunchTarget = true;
        } else if (!resolveInfo.activityInfo.packageName.equals(this.mCachedTarget.activityInfo.packageName)) {
            this.mCachedTarget = resolveInfo;
            if (!this.mAudioManager.isMusicActive()) {
                shouldLaunchTarget = true;
            }
        }
        forwardKeyCodeToComponent(context, new ComponentName(this.mCachedTarget.activityInfo.packageName, this.mCachedTarget.activityInfo.name), shouldLaunchTarget, keyCode, null);
    }

    private void forwardKeyCodeToComponent(Context context, ComponentName selectedReceiver, boolean launch, int keyCode, BroadcastReceiver cleanUpReceiver) {
        Intent mediaButtonDownIntent = new Intent("android.intent.action.MEDIA_BUTTON");
        KeyEvent downKe = new KeyEvent(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), 0, keyCode, 0);
        mediaButtonDownIntent.putExtra("android.intent.extra.KEY_EVENT", downKe);
        Intent mediaButtonUpIntent = new Intent("android.intent.action.MEDIA_BUTTON");
        KeyEvent upKe = new KeyEvent(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), 1, keyCode, 0);
        mediaButtonUpIntent.putExtra("android.intent.extra.KEY_EVENT", upKe);
        mediaButtonDownIntent.setComponent(selectedReceiver);
        mediaButtonUpIntent.setComponent(selectedReceiver);
        Trace.debug(TAG, "Forwarding Down and Up intent events to " + selectedReceiver + " Down Intent: " + mediaButtonDownIntent + " Down key:" + downKe + " Up Intent: " + mediaButtonUpIntent + " Up key:" + upKe);
        if (launch) {
            Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(selectedReceiver.getPackageName());
            if (launchIntent != null) {
                context.startActivity(launchIntent);
            }
        }
        context.sendOrderedBroadcast(mediaButtonDownIntent, null, cleanUpReceiver, null, -1, null, null);
        context.sendOrderedBroadcast(mediaButtonUpIntent, null, cleanUpReceiver, null, -1, null, null);
    }

    Set<EndpointId> getSupportedEndpoints() {
        return ImmutableSet.of(EndpointId.MUSIC_CONTROL);
    }

    boolean onReceive(ProtocolMessage message) {
        onMessageReceived(new PblInboundMusicMessage(message));
        return true;
    }

    boolean onRequest(EndpointRequest request, FrameworkState frameworkState) {
        Trace.debug(TAG, "Got request");
        switch (AnonymousClass1.$SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[request.getAction().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                Trace.debug(TAG, "Sending now playing info");
                sendMusicInfo();
                return true;
            default:
                Trace.debug(TAG, "No matching request found in MusicControlEndpoint, not handling.");
                return false;
        }
    }

    boolean onPrfRequest(EndpointRequest request, FrameworkState frameworkState) {
        Trace.debug(TAG, "Got request");
        switch (AnonymousClass1.$SwitchMap$com$getpebble$android$framework$endpoint$EndpointRequest$EndpointAction[request.getAction().ordinal()]) {
            case SMTPMessage.RETURN_FULL /*1*/:
                return true;
            default:
                return false;
        }
    }
}
